import { Catch, ExceptionFilter, HttpException, Inject } from "@nestjs/common";
import type { ArgumentsHost } from "@nestjs/common";
import { FastifyReply, FastifyRequest } from "fastify";
import { getReasonPhrase } from "http-status-codes";
import { WINSTON_MODULE_PROVIDER } from "nest-winston";
import { Logger } from "winston";

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
    constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger) { }

    catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<FastifyReply>();
        const request = ctx.getRequest<FastifyRequest>();
        const status = exception.getStatus();
        const results = exception.getResponse() as any;

        const message = (results.message ?? results) || getReasonPhrase(status)

        // 返回的对象
        const jsonData = {
            code: status,
            message,
            data: null
        };

        // 记录日志      
        this.logger.error(message);

        return response.code(status).send(jsonData);
    }
}


/**
 *   throw new HttpException({ error: '自定义错误描述', details: '附加信息' },  HttpStatus.BAD_REQUEST,{ cause: new Error('原始错误') })
 *   throw new HttpException('用户名已存在',HttpStatus.BAD_REQUEST)
 *   throw new BadRequestException('用户已存在');
 *   UnauthorizedException：401	用户未认证
 *   ForbiddenException	403	权限不足
 *   NotFoundException	404	资源不存在
 *   InternalServerErrorException	500	服务器内部错误
 */